<template>
  <div>
  <el-row :gutter="40" class="panel-group">
        <el-col :xs="12" :sm="12" :lg="12" class="card-panel-col">
          <div class="card-panel">
            <div class="card-panel-icon-wrapper icon-shopping">
              <svg-icon icon-class="shopping" class-name="card-panel-icon" />
            </div>
            <div class="card-panel-description">
              <div class="card-panel-text">
                项目
              </div>
              <el-select v-model="grantId" clearable  placeholder="请选择项目" style ="width:200%" @change="grantSelectChange">
                <el-option
                  v-for="item in grantOptions"
                  :key="item.grantId"
                  :label="item.grantName"
                  :value="item.grantId">
                </el-option>
              </el-select>
            </div>
          </div>
        </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('newVisitis')">
        <div class="card-panel-icon-wrapper icon-people">
          <svg-icon icon-class="peoples" class-name="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            计划数
          </div>
          <count-to :start-val="0" :end-val="plannedQuantity" :duration="2600" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    <el-col :xs="12" :sm="12" :lg="6" class="card-panel-col">
      <div class="card-panel" @click="handleSetLineChartData('messages')">
        <div class="card-panel-icon-wrapper icon-message">
          <svg-icon icon-class="message" class-name="card-panel-icon" />
        </div>
        <div class="card-panel-description">
          <div class="card-panel-text">
            已报名数
          </div>
          <count-to :start-val="0" :end-val="enrollQuantity" :duration="3000" class="card-panel-num" />
        </div>
      </div>
    </el-col>
    <span><a>你所在的单位：{{companyName}}</a></span>
    <el-button type="primary" @click="addCompanyForm" v-if="companyLvl===2 || companyLvl===1">增加派出单位</el-button>
    <el-button type="primary" @click="handleImport" v-if="companyLvl===2 || companyLvl===1">导入派出单位</el-button>
    <el-button type="primary" @click="handleExport" v-if="companyLvl===2 || companyLvl===1">导出派出单位</el-button>
    <el-button type="primary" @click="confirmFileUpload" v-if="companyLvl===2 || companyLvl===3  || companyLvl===1">报名清单盖章上传</el-button>
    <el-table :data="companyList">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" />
      <el-table-column label="单位名称" align="center" prop="comName" />
      <el-table-column label="计划数量" align="center" prop="plannedQuantity" />
      <el-table-column label="报名数量" align="center" prop="enrollQuantity" />
      <el-table-column label="级别" align="center" prop="lvl" />
      <el-table-column label="报请清单盖章件" align="center">
        <template slot-scope="scope">
              <el-link
                type="text"
                @click="downloadConfirmfile(scope.row)"
              >{{scope.row.confirmFileurl}}</el-link>
            </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDeleteCom(scope.row)"
            v-if="companyLvl===2 || companyLvl===1"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="getRegisterUrl(scope.row)"
            v-if="companyLvl===2 || companyLvl===1"
          >注册链接</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="getQrcode(scope.row)"
            v-if="companyLvl===3"
          >报名二维码</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-row>
      <!-- 添加或修改派出单位管理对话框 -->
      <el-dialog :title="title" :visible.sync="open" :close-on-click-modal="false" width="500px" append-to-body>
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="项目" prop="parentId">
            <el-input v-model="form.grantName" placeholder="项目" :readonly="true" :disabled="true"/>
          </el-form-item>
          <el-form-item label="上级单位" prop="parentId">
            <el-input v-model="form.parentComName" placeholder="上级单位"  :readonly="true" :disabled="true"/>
          </el-form-item>
          <el-form-item label="单位名称" prop="comName">
            <el-input v-model="form.comName" placeholder="请输入单位名称" />
          </el-form-item>
          <el-form-item label="是否可用" prop="isEnabled">
            <el-select v-model="form.isEnabled" placeholder="请选择是否启用">
              <el-option
                v-for="dict in yesnoOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
<!--          <el-form-item label="计划数量" prop="plannedQuantity">-->
<!--            <el-input v-model="form.plannedQuantity" placeholder="请输入计划数量" />-->
<!--          </el-form-item>-->
          <el-form-item label="级别" prop="lvl">
            <el-input v-model="form.lvl" placeholder="级别" :readonly="true" :disabled="true"/>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    <!-- 生成二维码对话框 -->
    <el-dialog :title="qrtitle" :visible.sync="qropen" width="500px" append-to-body>
      <div align="center">
        <span style="font-size: 18px">{{grantName}}</span>
        <span style="font-size: 18px">{{companyName}}</span>
        <div id="qrCode" ref="qrCodeUrl">
      </div>
      </div>
    </el-dialog>
    <!-- 派出单位导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?grantId=' + this.grantId + '&comParentId='+this.formCompanyId+'&lvl='+this.companyLvl"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
        <div class="el-upload__tip" slot="tip">
          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
        </div>
        <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 盖章文件上传对话框 -->
    <el-dialog :title="confirmupload.title" :visible.sync="confirmupload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".png, .jpg,.jpeg,.pdf"
        :headers="confirmupload.headers"
        :action="confirmupload.url + '?grantId=' + this.grantId + '&comParentId='+this.formCompanyId+'&lvl='+this.companyLvl"
        :disabled="confirmupload.isUploading"
        :on-progress="handleConfirmFileUploadProgress"
        :on-success="handleConfirmFileSuccess"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>
<!--        <div class="el-upload__tip" slot="tip">-->
<!--          <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>-->
<!--        </div>-->
        <div class="el-upload__tip" style="color:red" slot="tip">提示：请将盖章件进行拍照或转换成pdf后上传！</div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitConfirmFileForm">确 定</el-button>
        <el-button @click="confirmupload.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import CountTo from 'vue-count-to'
import {listGrantAll} from "@/api/grant/grant";
import {
  addGrcompany,
  getGrcompany,
  getUserCompanyPanelData,
  updateGrcompany,
  getCompanyImportTemplate,
  userCompanyPanelexport, delGrcompany,downloadConfirmfile
} from "@/api/grant/grcompany"
import QRCode from "qrcodejs2";
import {getToken} from "@/utils/auth";
import {exportExaminergrant} from "@/api/grant/examinergrant";
export default {
  components: {
    CountTo
  },
  data() {
    return {
      open: false,
      qropen: false,
      qrFlag: false,
      qrtitle: '报名二维码',
      grantOptions: [],
      companyList: [],
      yesnoOptions: [],
      title: '派出单位新增',
      grantId: undefined,
      plannedQuantity:0, //计划数
      enrollQuantity:0 , //报名数
      companyName:'请先选择项目',
      enrollHost: undefined, //报名的域名，从后台系统配置表获取
      grantName :undefined,
      companyLvl: 0,
      companyId: undefined,
      formCompanyId: undefined,
      form:{
        parentComName: undefined,
        comName: undefined,
        isEnabled: undefined,
        grantName: undefined,
        plannedQuantity: 0,
        lvl: undefined,
        parentId: undefined
      },
      // 表单校验
      rules: {
        comName: [
          { required: true, message: "单位名称不能为空", trigger: "blur" }
        ],
        grantId: [
          { required: true, message: "项目不能为空", trigger: "blur" }
        ],
        plannedQuantity: [{
          required:true,message:"必须填写数量",trigger: "blur"
        }]
      },
      // 派出单位导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/grant/grcompany/importComapny"
      },
      //盖章文件上传参数
      confirmupload:{
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "报名文件盖章确认",
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/grant/grcompany/confirmFileUpload"
      }
    }
  },
  created() {
    let query ={};
    query["isEnabled"]="0";
    listGrantAll(query).then(res=>{
      this.grantOptions = res.data;
      this.grantId=res.data[res.data.length-1].grantId;
      this.grantName=res.data[res.data.length-1].grantName;
      this.getUserCompanyPanelData();
    })
    this.getDicts("sys_yes_no").then(response => {
      this.yesnoOptions = response.data;
    });
  },
  methods: {
    handleSetLineChartData(type) {
      this.$emit('handleSetLineChartData', type)
    },
    grantSelectChange(value){
      this.grantId = value;
      this.getUserCompanyPanelData();
    },
    getUserCompanyPanelData(){
      let query = {};
      query['grantId'] = this.grantId;
      getUserCompanyPanelData(query).then(res =>{
        this.companyList = res.data.companyList;
        this.plannedQuantity = res.data.plannedQuantity;
        this.enrollQuantity = res.data.enrollQuantity;
        this.companyName = res.data.companyName;
        this.companyLvl = res.data.lvl;
        this.companyId  = res.data.companyId;
        this.formCompanyId = res.data.formCompanyId;
        this.enrollHost = res.data.enrollHost;
      })
    }
    ,handleUpdate(row){
      if(this.companyLvl == 3){
        this.msgError('对不起，你不能修改信息');
        return;
      }
      getGrcompany(row.id).then(response => {
        this.form = response.data;
        this.form.parentComName = this.companyName;
        this.form.grantName = this.grantName;
        this.open = true;
        this.title = "修改派出单位";
      });
    },addCompanyForm(){
      if(this.companyLvl == 3){
        this.msgError('对不起，你不能新增派出单位');
        return;
      }
      this.title = "新增派出单位"
      this.form.parentComName = this.companyName;
      this.form.grantName = this.grantName;
      this.form.grantId = this.grantId;
      this.form.parentId = this.formCompanyId;
      this.form.lvl = this.companyLvl+1;
      this.open = true;
    },submitForm(){
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != undefined) {
            updateGrcompany(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getUserCompanyPanelData();
              }
            });
          } else {
            addGrcompany(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getUserCompanyPanelData();
              }
            });
          }
        }
      });
    },cancel(){
      this.open=false;
    },getRegisterUrl(row){
      // let registerUrl = process.env.VUE_APP_BASE_API;
      let registerUrl = window.location.host;
      registerUrl = registerUrl+"/userregister?companyId="+row.id+"&grantId="+row.grantId;
      let registerTitle = "";
      this.$alert(registerUrl, '管理员注册链接', {
        confirmButtonText: '确定',
      });
    },getQrcode(row){
      this.qropen = true;
      if(this.qrFlag) {
        this.delQrcode();
      }
      this.qrFlag = true;
      let enrollUrl=this.enrollHost;
      setTimeout(function() {
        enrollUrl+="/#/loginPage?grantId="+row.grantId+"&companyId="+row.id;
        console.log(enrollUrl);
        let a = new QRCode('qrCode', {
          text: enrollUrl, // 需要转换为二维码的内容
          width: 200,
          height: 200,
          colorDark: "black", //#000000为黑色
          colorLight: "white",
        });
      },200);

    }// 清空二维码,避免生成多个二维码
    ,delQrcode(){
        this.$refs.qrCodeUrl.innerHTML = ""
    },exportCompanyForm(){
      if(this.companyLvl == 3){
        this.msgError('对不起，你不能导出派出单位');
        return;
      }

    },
    importCompanyForm(){
      if(this.companyLvl == 3){
        this.msgError('对不起，你不能新增派出单位');
        return;
      }
    },
    /** 导入 按钮操作 */
    handleImport() {
      this.upload.title = "派出单位导入";
      this.upload.open = true;
    },
    handleExport(){
      let query = {};
      query['grantId'] = this.grantId;
      let registerUrl = window.location.host;
      query['registerUrl'] = registerUrl;
      this.$confirm('是否确认导出所有派出单位数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return userCompanyPanelexport(query);
      }).then(response => {
        this.download(response.msg);
      }).catch(function() {});
    },
    /** 下载模板操作 */
    importTemplate() {
      return getCompanyImportTemplate().then(res=>{
        this.download(res.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", { dangerouslyUseHTMLString: true });
      this.getUserCompanyPanelData();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },handleDeleteCom(row){
      this.$confirm('是否确认删除派出单位管理编号为"' + row.id + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delGrcompany(row.id);
      }).then(() => {
        this.getUserCompanyPanelData();
        this.msgSuccess("删除成功");
      }).catch(function() {this.getUserCompanyPanelData();});
    }
    ,confirmFileUpload(){
      this.confirmupload.title = "报文清单盖章上传";
      this.confirmupload.open = true;
    },
    // 文件上传中处理
    handleConfirmFileUploadProgress(event, file, fileList) {
      this.confirmupload.isUploading = true;
    },
    // 文件上传成功处理
    handleConfirmFileSuccess(response, file, fileList) {
      this.confirmupload.open = false;
      this.confirmupload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "上传结果", { dangerouslyUseHTMLString: true });
      this.getUserCompanyPanelData();
    },
    // 提交上传文件
    submitConfirmFileForm() {
      console.log(this.confirmupload.fileList);
      this.$refs.upload.submit();
    },
    downloadConfirmfile(row){
      let query = {};
      query['confirmFileurl'] = row.confirmFileurl;
      downloadConfirmfile(query).then(res=>{
        // this.download(res.msg);
        window.open(res.msg, '_blank', 'noopener,noreferrer');
      });
    }
  }
}
</script>

<style lang="scss" scoped>
.panel-group {
  margin-top: 18px;

  .card-panel-col {
    margin-bottom: 32px;
  }

  .card-panel {
    height: 108px;
    cursor: pointer;
    font-size: 12px;
    position: relative;
    overflow: hidden;
    color: #666;
    background: #fff;
    box-shadow: 4px 4px 40px rgba(0, 0, 0, .05);
    border-color: rgba(0, 0, 0, .05);

    &:hover {
      .card-panel-icon-wrapper {
        color: #fff;
      }

      .icon-people {
        background: #40c9c6;
      }

      .icon-message {
        background: #36a3f7;
      }

      .icon-money {
        background: #f4516c;
      }

      .icon-shopping {
        background: #34bfa3
      }
    }

    .icon-people {
      color: #40c9c6;
    }

    .icon-message {
      color: #36a3f7;
    }

    .icon-money {
      color: #f4516c;
    }

    .icon-shopping {
      color: #34bfa3
    }

    .card-panel-icon-wrapper {
      float: left;
      margin: 14px 0 0 14px;
      padding: 16px;
      transition: all 0.38s ease-out;
      border-radius: 6px;
    }

    .card-panel-icon {
      float: left;
      font-size: 48px;
    }

    .card-panel-description {
      float: left;
      font-weight: bold;
      margin: 26px;
      margin-left: 0px;

      .card-panel-text {
        line-height: 18px;
        color: rgba(0, 0, 0, 0.45);
        font-size: 16px;
        margin-bottom: 12px;
      }

      .card-panel-num {
        font-size: 20px;
      }
    }
  }
}

@media (max-width:550px) {
  .card-panel-description {
    display: none;
  }

  .card-panel-icon-wrapper {
    float: none !important;
    width: 100%;
    height: 100%;
    margin: 0 !important;

    .svg-icon {
      display: block;
      margin: 14px auto !important;
      float: none !important;
    }
  }
}
</style>
